import Permission from './permission'
import User from './user'
import { isString } from '../utils/index'

class UserPermission {
  constructor() {
    // 组
    this.state = [
      // {
      //   id: '', //
      //   uid: '',
      //   pid: '' //
      // }
    ]
    this.instance = null
  }

  static getInstance() {
    if (!this.instance) {
      this.instance = new UserPermission()
    }
    return this.instance
  }

  /**
   * @param {*} pid
   */
  checkPermission(pid) {
    let valid = Permission.state.some(v => {
      return v.pid === pid
    })
    return valid
  }
  /**
   * @param {*} uid
   */
  checkUser(uid) {
    let valid = User.state.some(v => {
      return v.uid === uid
    })
    return valid
  }
  /**
   * 设置
   * @param {*} item
   */
  setState(item) {
    if (!item) {
      return false
    }
    if (isString(item.pid) && isString(item.uid)) {
      let checkPermission = this.checkPermission(item.pid)
      if (!checkPermission) {
        return false
      }
      let checkUser = this.checkUser(item.uid)
      if (!checkUser) {
        return false
      }
      item['id'] = this.state.length
      item['code'] = `${item.pid}_${item.uid}`
      let valid = this.state.some(v => {
        return v.code === item['code']
      })
      if (!valid) {
        this.state.push(item)
      }
    }
    return false
  }
  /**
   * 获取
   * @param {object} item
   */
  getState(item = { pid: '', uid: '' }) {
    if (item && (item.pid || item.uid)) {
      if (isString(item.pid) && isString(item.uid)) {
        return this.state.filter(v => {
          return v.code === `${item.pid}_${item.uid}`
        })
      } else if (isString(item.pid)) {
        return this.state.filter(v => {
          return v.pid === item.pid
        })
      } else if (isString(item.uid)) {
        return this.state.filter(v => {
          return v.uid === item.uid
        })
      }
    }
    return []
  }
}
let _userPermission = UserPermission.getInstance()
export default _userPermission
